package com.clouddot.baipai.ui.activity;

import android.content.Intent;
import android.hardware.Camera;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerISettingActivityComponent;
import com.clouddot.baipai.contract.ISettingActivityContract;
import com.clouddot.baipai.http.BanPaiRetrofitHelper;
import com.clouddot.baipai.http.TableRetrofitHelper;
import com.clouddot.baipai.http.entity.response.getAllClassResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.infrastructure.environment.environment;
import com.clouddot.baipai.infrastructure.environment.initial.InitialAppUpdate;
import com.clouddot.baipai.module.SettingActivityModule;
import com.clouddot.baipai.ui.Dialog.H_updateDailog;
import com.clouddot.baipai.ui.Dialog.V_updateDailog;
import com.clouddot.baipai.ui.adapter.AllClassAdapter;
import com.clouddot.baipai.util.FtpUtil.AnalyzeXMLUtil;
import com.clouddot.baipai.util.FtpUtil.DownFileUtil;
import com.clouddot.baipai.util.FtpUtil.XMLBean;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.SlideSwitch;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseActivity;

import java.util.ArrayList;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.COMETOSET;

/**
 * Created by wxy on 2018/05/27.
 *
 * @author wxy
 * @date on 2018/05/27 11:32
 * 设置 的主页面
 */
public class SettingActivity extends BaseActivity implements ISettingActivityContract.IView {
    private AllClassAdapter allClassAdapter;
    private String selectIndex;
    private String selectIndexText;
    private boolean isReSetClass = false;
    private boolean isReSetIP = false;
    private ArrayList<getAllClassResponse> responses = new ArrayList<>();
    @Inject
    ISettingActivityContract.IPresenter mPresenter;

    @BindView(R.id.img_back)
    ImageView img_back;
    @BindView(R.id.img_net)
    ImageView img_net;

    @BindView(R.id.ed_ServerIP)
    EditText ed_ServerIP;
    @BindView(R.id.sp_className)
    Spinner sp_className;

    @BindView(R.id.Sw_scanFace)
    SlideSwitch Sw_scanFace;
    @BindView(R.id.ed_scanFaceURL)
    EditText ed_scanFaceURL;
    @BindView(R.id.ed_scanFaceVerify)
    EditText ed_scanFaceVerify;
    @BindView(R.id.tv_scanFaceVerify)
    TextView tv_scanFaceVerify;
    @BindView(R.id.tv_scanFaceUrl)
    TextView tv_scanFaceUrl;
    @BindView(R.id.btn_saveScanFaceConfig)
    Button btn_saveScanFaceConfig;

    @BindView(R.id.Sw_autoUpdate)
    SlideSwitch Sw_autoUpdate;
    @BindView(R.id.radio)
    RadioGroup radio;
    @BindView(R.id.morning)
    RadioButton morning;
    @BindView(R.id.night)
    RadioButton night;
    @BindView(R.id.Sw_clockUpdate)
    SlideSwitch Sw_clockUpdate;

    @BindView(R.id.Sw_AutoTakePhoto)
    SlideSwitch Sw_AutoTakePhoto;
    @BindView(R.id.Sw_LockServer)
    SlideSwitch Sw_LockServer;
    @BindView(R.id.ed_backMainTime)
    EditText ed_backMainTime;
    @BindView(R.id.ed_loginTime)
    EditText ed_loginTime;
    @BindView(R.id.tv_AutoTakePhoto)
    TextView tv_AutoTakePhoto;
    @BindView(R.id.tv_machineNo)
    TextView tv_machineNo;

    @Override
    protected int getContentViewId() {
        if (Env.getAppContext().banPaiType == 0) {
            return R.layout.h_activity_setting;
        } else {
            return R.layout.v_activity_setting;

        }
    }

    @Override
    protected void initVariables() {
        DaggerISettingActivityComponent.builder().settingActivityModule(new SettingActivityModule(this)).build().inject(this);
        mPresenter.getAllClassList();
    }

    @Override
    protected void initViews() {
        try {
            InitialSlideSwith();
            ed_ServerIP.setText(Env.getAppContext().IP);
            ed_loginTime.setText(Env.getAppContext().LoginTime + "");
            ed_backMainTime.setText(Env.getAppContext().backToMainTime + "");
            ed_scanFaceVerify.setText(Env.getAppContext().scanVerify + "");
            ed_scanFaceURL.setText(Env.getAppContext().scanfaceUrl);
            tv_machineNo.setText("设备号： " + Env.getAppContext().carddevid + "\n版本号： " + Env.getAppContext().Version + ".0");

            Sw_AutoTakePhoto.setSlideListener(isAutoTakePhotolistener);
            if (Camera.open() != null) {
                Sw_scanFace.setSlideListener(isOpenScanlistener);
            }
            Sw_autoUpdate.setSlideListener(isAutoUpdatelistener);
            Sw_clockUpdate.setSlideListener(isClockUpdatelistener);
            Sw_LockServer.setSlideListener(isOpenServicelistener);

            radio.setOnCheckedChangeListener(radioGroupListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void loadData() {

    }

    @OnClick({R.id.img_back, R.id.btn_saveIP, R.id.btn_bindClass, R.id.btn_saveScanFaceConfig,
            R.id.tv_HeadUpdate, R.id.btn_otherConfig, R.id.img_net})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                if (isReSetIP && !isReSetClass) {
                    ToastUtil.showToast(SettingActivity.this, "更改IP后请重新绑定班级");
                    return;
                }
                Intent intent = new Intent();
                intent.putExtra("reSetClass", isReSetClass);
                intent.putExtra("reSetIP", isReSetIP);
                setResult(COMETOSET, intent);
                this.finish();
                break;
            case R.id.btn_saveIP:
                String IP = ed_ServerIP.getText().toString().trim();
                if (!IP.equals(Env.getAppContext().IP)) {
                    try {
                        XMLBean xmlBean = new XMLBean();
                        xmlBean.setData("no data");
                        xmlBean.setUrl(IP);
                        xmlBean.setVersion("1");
                        AnalyzeXMLUtil.modifyXml(Env.getAppContext().CONFIGPATH, xmlBean);
                        Env.getAppContext().IP = IP;
                        Env.getAppContext().position = 0;
                        Env.getAppContext().ClassID = "";
                        Env.getAppContext().ClassName = "";
                        responses.clear();
                        if (allClassAdapter != null) allClassAdapter.notifyDataSetChanged();
                        BanPaiRetrofitHelper.getInstance(this).reSet();
                        TableRetrofitHelper.getInstance(this).reSet();
                        isReSetIP = true;
                        ToastUtil.showToast(this, "IP地址保存成功");
                        mPresenter.getAllClassList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.btn_bindClass:
                if (responses.isEmpty()) return;
                if (!Env.getAppContext().ClassID.equals(selectIndex)) {
                    mPresenter.bindBanPai(selectIndex, Env.getAppContext().carddevid);
                }
                break;
            case R.id.btn_saveScanFaceConfig:
                if (Env.getAppContext().openScan) {
                    if (TextUtils.isEmpty(ed_scanFaceURL.getText().toString().trim())) {
                        ToastUtil.showToast(this, "人脸识别URL为空");
                        return;
                    }
                    if (TextUtils.isEmpty(ed_scanFaceVerify.getText().toString().trim())) {
                        ToastUtil.showToast(this, "识别度不能为空");
                        return;
                    }
                    String scanFaceUrl = ed_scanFaceURL.getText().toString().trim();
                    int score = (int) Math.floor(Double.parseDouble(ed_scanFaceVerify.getText().toString().trim()));
                    if (!scanFaceUrl.equals(Env.getAppContext().scanfaceUrl)) {

                        Env.getAppContext().scanfaceUrl = scanFaceUrl;
                        Env.getAppContext().scanVerify = score;

                        Env.getSpHelper().put("scanVerify", score);
                        Env.getSpHelper().put("scanFaceUrl", scanFaceUrl);

                        ToastUtil.showToast(this, "人脸识别配置保存成功");
                    }
                }
                break;
            case R.id.tv_HeadUpdate:
                startUpdate();
                break;
            case R.id.btn_otherConfig:
                if (TextUtils.isEmpty(ed_backMainTime.getText().toString().trim())) {
                    ToastUtil.showToast(this, "未操作时限为空");
                    return;
                }
                if (TextUtils.isEmpty(ed_loginTime.getText().toString().trim())) {
                    ToastUtil.showToast(this, "登录时间为空");
                    return;
                }

                int backToMainTime = Integer.parseInt(ed_backMainTime.getText().toString());
                int loginTime = Integer.parseInt(ed_loginTime.getText().toString());

                Env.getAppContext().backToMainTime = backToMainTime;
                Env.getAppContext().LoginTime = loginTime;

                Env.getSpHelper().put("backMainTime", backToMainTime);
                Env.getSpHelper().put("loginTime", loginTime);

                ToastUtil.showToast(this, "保存成功");

                break;

            case R.id.img_net:
                Env.getAppContext().isOpenService = false;
                Intent intents =  new Intent(Settings.ACTION_SETTINGS);
//                Intent intent =  new Intent(Settings.ACTION_WIFI_SETTINGS);
                startActivityForResult(intents,1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Env.getAppContext().isOpenService = (boolean) Env.getSpHelper().get("isOpenService", false);


    }

    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            isReSetClass = true;
            Env.getAppContext().ClassID = selectIndex;
            Env.getAppContext().ClassName = selectIndexText;
            Env.getSpHelper().put("ClassPosition", Env.getAppContext().position);
            ToastUtil.showToast(this, "绑定班级成功");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    img_back.performClick();
                }
            }, 1500);
        } else if (flag == 2) {
            refreshAllClassName(object);
        }
    }

    private void refreshAllClassName(Object object) {
        responses = (ArrayList<getAllClassResponse>) object;
        allClassAdapter = new AllClassAdapter(this);
        allClassAdapter.setDatas(responses);
        selectIndex = responses.get(Env.getAppContext().position).getClassId();
        selectIndexText = responses.get(Env.getAppContext().position).getGradeClassName();
        sp_className.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectIndex = responses.get(position).getClassId();
                selectIndexText = responses.get(position).getGradeClassName();
                Env.getSpHelper().put("ClassPosition", position);
                Env.getAppContext().position = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_className.setAdapter(allClassAdapter);
        sp_className.setSelection(Env.getAppContext().position);
    }

    @Override
    public void fail(int flag, String errMsg) {
        ToastUtil.showToast(this, errMsg);
    }

    private void InitialSlideSwith() throws Exception {

        boolean isAuto = (boolean) Env.getSpHelper().get("isAuto", true);
        boolean isClocksUpdate = (boolean) Env.getSpHelper().get("ClockUpdate", false);
        boolean isAutoTakePhoto = (boolean) Env.getSpHelper().get("isAutoTakePhoto", false);
        boolean isOpenService = (boolean) Env.getSpHelper().get("isOpenService", true);
        boolean openScan = (boolean) Env.getSpHelper().get("openScan", false);

        if (isClocksUpdate) {
            radio.setVisibility(View.VISIBLE);
            int time = (int) Env.getSpHelper().get("AutoUpdateTime", 07);
            if (time == 07) {
                morning.setChecked(true);
            } else {
                night.setChecked(true);
            }
            Sw_clockUpdate.setState(true);
        } else {
            radio.setVisibility(View.GONE);
            Sw_clockUpdate.setState(false);
        }

        if (isAuto) {
            Sw_autoUpdate.setState(true);
        } else {
            Sw_autoUpdate.setState(false);
        }


        if (isOpenService) {
            Sw_LockServer.setState(true);
        } else {
            Sw_LockServer.setState(false);
        }

        if (Camera.open() == null) {

            Sw_AutoTakePhoto.setVisibility(View.GONE);
            tv_AutoTakePhoto.setVisibility(View.GONE);
            ed_scanFaceURL.setVisibility(View.GONE);
            ed_scanFaceVerify.setVisibility(View.GONE);
            tv_scanFaceUrl.setVisibility(View.GONE);
            tv_scanFaceVerify.setVisibility(View.GONE);
            btn_saveScanFaceConfig.setVisibility(View.GONE);
        } else {
            Sw_AutoTakePhoto.setVisibility(View.VISIBLE);
            tv_AutoTakePhoto.setVisibility(View.VISIBLE);
            ed_scanFaceURL.setVisibility(View.VISIBLE);
            ed_scanFaceVerify.setVisibility(View.VISIBLE);
            tv_scanFaceUrl.setVisibility(View.VISIBLE);
            tv_scanFaceVerify.setVisibility(View.VISIBLE);
            btn_saveScanFaceConfig.setVisibility(View.VISIBLE);
            if (isAutoTakePhoto) {
                Sw_AutoTakePhoto.setState(true);
            } else {
                Sw_AutoTakePhoto.setState(false);
            }
        }
        if (openScan) {
            ed_scanFaceURL.setVisibility(View.VISIBLE);
            ed_scanFaceVerify.setVisibility(View.VISIBLE);
            tv_scanFaceUrl.setVisibility(View.VISIBLE);
            tv_scanFaceVerify.setVisibility(View.VISIBLE);
            btn_saveScanFaceConfig.setVisibility(View.VISIBLE);
            Sw_scanFace.setState(true);
        } else {
            ed_scanFaceURL.setVisibility(View.GONE);
            ed_scanFaceVerify.setVisibility(View.GONE);
            tv_scanFaceUrl.setVisibility(View.GONE);
            tv_scanFaceVerify.setVisibility(View.GONE);
            btn_saveScanFaceConfig.setVisibility(View.GONE);
            Sw_scanFace.setState(false);
        }
    }

    private SlideSwitch.SlideListener isOpenScanlistener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            ed_scanFaceURL.setVisibility(View.VISIBLE);
            ed_scanFaceVerify.setVisibility(View.VISIBLE);
            tv_scanFaceUrl.setVisibility(View.VISIBLE);
            tv_scanFaceVerify.setVisibility(View.VISIBLE);

            btn_saveScanFaceConfig.setVisibility(View.VISIBLE);

            Env.getSpHelper().put("openScan", true);
            Env.getAppContext().openScan = true;

        }

        @Override
        public void close() throws Exception {
            ed_scanFaceURL.setVisibility(View.GONE);
            ed_scanFaceVerify.setVisibility(View.GONE);
            tv_scanFaceUrl.setVisibility(View.GONE);
            tv_scanFaceVerify.setVisibility(View.GONE);
            btn_saveScanFaceConfig.setVisibility(View.GONE);
            Env.getSpHelper().put("openScan", false);
            Env.getAppContext().openScan = false;
        }
    };

    private SlideSwitch.SlideListener isClockUpdatelistener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            radio.setVisibility(View.VISIBLE);
            int time = (int) Env.getSpHelper().get("ClockUpdateTime", 07);
            if (time == 07) {
                morning.setChecked(true);
            } else {
                night.setChecked(true);
            }
            Env.getSpHelper().put("ClockUpdate", true);
            Env.getAppContext().isClocksUpdate = true;

        }

        @Override
        public void close() throws Exception {
            radio.setVisibility(View.GONE);
            Env.getSpHelper().put("ClockUpdate", false);
            Env.getAppContext().isClocksUpdate = false;


        }
    };

    private SlideSwitch.SlideListener isAutoUpdatelistener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            Env.getSpHelper().put("isAuto", true);
            Env.getAppContext().isAutoUpdate = true;

        }

        @Override
        public void close() throws Exception {
            Env.getSpHelper().put("isAuto", false);
            Env.getAppContext().isAutoUpdate = false;


        }
    };

    private SlideSwitch.SlideListener isAutoTakePhotolistener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            Env.getSpHelper().put("isAutoTakePhoto", true);
            Env.getAppContext().isAutoTakePhoto = true;

        }

        @Override
        public void close() throws Exception {
            Env.getSpHelper().put("isAutoTakePhoto", false);
            Env.getAppContext().isAutoTakePhoto = false;

        }
    };

    private SlideSwitch.SlideListener isOpenServicelistener = new SlideSwitch.SlideListener() {
        @Override
        public void open() throws Exception {
            Env.getSpHelper().put("isOpenService", true);
            Env.getAppContext().isOpenService = true;

        }

        @Override
        public void close() throws Exception {
            Env.getSpHelper().put("isOpenService", false);
            Env.getAppContext().isOpenService = false;

        }
    };

    private RadioGroup.OnCheckedChangeListener radioGroupListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {

            switch (radioGroup.getCheckedRadioButtonId()) {
                case R.id.morning:
                    Env.getSpHelper().put("ClockUpdateTime", 07);
                    break;
                case R.id.night:
                    Env.getSpHelper().put("ClockUpdateTime", 19);
                    break;
            }

            Env.getAppContext().autoUpdateTime = (int) Env.getSpHelper().get("ClockUpdateTimev", 07);
        }
    };

    private void startUpdate() {

        ToastUtil.showToast(this, "正在检查版本...");

        if (Env.getAppContext().isUpdata) {
            if (Env.getAppContext().banPaiType == 0) {
                final H_updateDailog dailog = new H_updateDailog(SettingActivity.this);
                dailog.showDialog();
                dailog.getTextView().setText("新版本版本号: " + Env.getAppContext().updateVer + ".0\n" + Env.getAppContext().updateTip);
                dailog.getBtnView()[1].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dailog.closeDialog();
                    }
                });
                dailog.getBtnView()[0].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DownFileUtil.downloadFile(SettingActivity.this);
                        dailog.closeDialog();
                    }
                });
            } else {
                final V_updateDailog dailog = new V_updateDailog(SettingActivity.this);
                dailog.showDialog();
                dailog.getTextView().setText("新版本 " + Env.getAppContext().updateVer + ".0\n" + Env.getAppContext().updateTip);
                dailog.getBtnView()[1].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dailog.closeDialog();
                    }
                });
                dailog.getBtnView()[0].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        DownFileUtil.downloadFile(SettingActivity.this);
                        dailog.closeDialog();
                    }
                });
            }
        } else {
            ToastUtil.showToast(Env.getContent(), "当前版本是最新版本");
        }

        try {
            new InitialAppUpdate(environment.getInstance()).reinitial();

        } catch (Exception e) {
            Env.error(e);
            e.printStackTrace();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            img_back.performClick();
            return false;
        }
        return true;
    }


}
